#include"doubleList.h"


//创建一个节点
ListNode* BuyListNode(LTDataType x)
{
 ListNode* newnode;
 newnode = (ListNode*)malloc(sizeof(ListNode));
 if(newnode==NULL)
 {
   printf("malloc fail\n");
   exit(-1);
 }
 newnode->data = x;
 newnode->next = NULL;
 newnode->prev = NULL;
 return newnode;
}

//初始化链表
ListNode* ListInit()
{
 ListNode* phead = BuyListNode(-1);
 phead->next = phead;
 phead->prev = phead;
 return phead;
}

//销毁链表
void ListDestory(ListNode* phead)
{
 assert(phead);
 ListNode* cur = phead->next ;
 ListNode* next = cur->next;
 while(cur!=phead)
 {
   free(cur);
   cur = next;
 }
 free(phead);
}

//打印双向链表
void ListPrint(ListNode* phead)
{
 assert(phead);
 ListNode* cur = phead->next;
 while(cur!=phead)
 {
   printf("%d ",cur->data);
   cur = cur->next;
 }
 printf("\n");

}
//查找元素
ListNode* ListFind(ListNode* phead, LTDataType x)
{
 assert(phead);
 ListNode* cur = phead->next;//从头结点的后一个结点开始查找
 while (cur != phead)//当cur指向头结点时，说明链表已遍历完毕
 {
   if (cur->data == x)
   {
     return cur;//返回目标结点的地址
   }
   cur = cur->next;
 }
 return NULL;//没有找到目标结点
}

//头插
void ListPushFront(ListNode* phead, LTDataType x)
{
 assert(phead);
 ListNode* newnode = BuyListNode(x);

 newnode->next = phead->next;
 phead->next->prev = newnode;
 phead->next = newnode;
 newnode->prev = phead;
}

//尾插
void ListPushBack(ListNode* phead,LTDataType x)
{
  assert(phead);
  ListNode* newnode = BuyListNode(x);
  phead->prev->next = newnode;
  newnode->prev = phead->prev;
  newnode->next = phead;
  phead->prev = newnode;
}
//指定位置之后插入
void ListInsert(ListNode* pos,LTDataType x)
{
  assert(pos);
  ListNode* newnode = BuyListNode(x);
  newnode->next = pos->next;
  pos->next->prev = newnode;
  newnode->prev = pos;
  pos->next = newnode;
}
//头删

void ListPopFront(ListNode* phead)
{
  assert(phead);
  assert(phead->next!=phead);
  ListNode* cur = phead->next;
  phead->next = cur->next;
  cur->next->prev = phead;
  free(cur);
  cur=NULL;
}
//删除指定节点
void ListErase(ListNode* pos)
{
  assert(pos);
  pos->prev->next = pos->next;
  pos->next->prev = pos->prev;
  free(pos);

}
